package com.gy.spring.mvc.common.interceptor;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Repository;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.gy.spring.mvc.common.tools.R;

/**
 * TODO 全局异常捕捉
 *
 * @author geYang
 * @date 2018-04-10
 */
//@Repository
public class ExceptionHandler extends AbstractHandlerExceptionResolver {


    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response,
                                              Object handler, Exception e) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

        R r = null;
        if (e instanceof MyException) {
            r = R.err((MyException) e);
            logger.info(e.getMessage(), e);
        } else {
            r = R.err("未定义异常");
            logger.info("未定义异常", e);
        }
        e.printStackTrace();
        try {
            response.getOutputStream().write(JSON.toJSONString(r).getBytes("UTF-8"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 判断是否为AJAX请求
     */
    public boolean isAjax(HttpServletRequest request) {
        return "XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"));
    }

    public ModelAndView jsonResult(int code, String message) {
        ModelAndView mv = new ModelAndView();
        FastJsonJsonView view = new FastJsonJsonView();
        view.setAttributesMap((JSONObject) JSON.toJSON(R.err(code, message)));
        mv.setView(view);
        return mv;
    }
}
